/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.J2SE.Thread;

/**
 *
 * @author kylin
 */
public class ProducerConsumer {
    public static void main(String args[]){
        Basket b=new Basket();
        Producer p=new Producer(b);
        Consumer c=new Consumer(b);
        Thread thp=new Thread(p);
        Thread thc=new Thread(c);
        thp.start();
        thc.start();
    }
}

class Bun{
    int id;
    public Bun(int id){
        this.id=id;
    }
    public int getId(){
        return id;
    }
}
class Basket{
    int index=0;
    Bun[] basket=new Bun[6];
    
    public synchronized void push(Bun b){
        while(index==basket.length){
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notify();
        basket[index]=b;
        index++;
    }
    
    public synchronized Bun pop(){
        while(index==0){
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        return basket[index];
    }
}
class Producer implements Runnable{
    Basket basket=null;
    
    public Producer(Basket basket){
        this.basket=basket;
    }
    
    public void produce(){
        for(int i=0;i<20;i++){
            Bun b=new Bun(i);
            basket.push(b);
            System.out.println("produced one bun:"+b.getId());
            try{
                Thread.sleep((int)Math.random()*200);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    
    public void run(){
        produce();
    }
}
class Consumer implements Runnable{
    Basket basket=null;
    
    public Consumer(Basket basket){
        this.basket=basket;
    }
    
    public void consume(){
        for(int i=0;i<20;i++){
            Bun b=basket.pop();
            System.out.println("consume one bun:"+b.getId());
            try{
                Thread.sleep((int)Math.random()*1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    
    public void run(){
        consume();
    }
}